package com.tutu.user.security;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tutu.common.GlobalConstants;
import com.tutu.common.util.Constants;
import com.tutu.common.util.JsonReturnObject;

/**
 * 
 * @author tutu
 *	@date 2013-11-22
 *	@company cjcc
 *	@version ssi_1.0 1.0
 */
@Service("myAccessDeniedHandler")
public class MyAccessDeniedHandler implements AccessDeniedHandler {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException, ServletException {
		boolean isAjax = Constants.isAjaxRequest(request);
		logger.info("是否是ajax请求：" + isAjax);
        if(!isAjax){
//            RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/comm/error.jsp");
        	JsonReturnObject<String> jsonReturnObject = new JsonReturnObject<String>(false, "操作系统权限不足!");
            GlobalConstants.setSessionMessage(request.getSession(), jsonReturnObject);
//            RequestDispatcher dispatcher = request.getRequestDispatcher("/logout");
//            dispatcher.forward(request, response);
            response.sendRedirect(request.getContextPath() + "/logout");
        }else{
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain");
            JsonReturnObject<String> jsonReturnObject = new JsonReturnObject<String>(false,"权限不足");
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(jsonReturnObject);
            response.getWriter().write(json);
            response.getWriter().close();
        }
	}

}
